/*
 * PACKAGE NAME: com.jodinfo.outmirror.api.tabledefine.service
 * FILE    NAME: TableDefineDaoImpl.java
 * COPYRIGHT: Copyright(c) © 2016 heroj Company Ltd. All Rights Reserved
 */ 
package com.jodinfo.outmirror.api.tabledefine.service;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Tag;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.util.Base64;
import com.hero.common.web.context.UserContext;
import com.hero.common.web.excel.util.ExcelExport;
import com.hero.common.web.exeption.WebException;
import com.hero.core.constant.SysConstant;
import com.hero.core.entity.IPlatformUser;
import com.hero.core.entity.PageResult;
import com.hero.core.entity.ResponseEntity;
import com.hero.core.exception.AbstractGenericException;
import com.hero.core.exception.BusinessException;
import com.hero.core.util.DateUtils;
import com.hero.core.util.IdWorker;
import com.hero.core.util.ListSortUtil;
import com.hero.core.util.StringUtils;
import com.hero.core.util.ValidationUtil;
import com.jodinfo.outmirror.api.Dymcform.service.DymcformDmlService;
import com.jodinfo.outmirror.api.Dymcform.service.DymcformQueryService;
import com.jodinfo.outmirror.api.columndefine.entity.ColumnDefineEntity;
import com.jodinfo.outmirror.api.columndefine.service.ColumnDefineDmlService;
import com.jodinfo.outmirror.api.columndefine.service.ColumnDefineQueryService;
import com.jodinfo.outmirror.api.tabledefine.entity.SubTableDefineEntity;
import com.jodinfo.outmirror.api.tabledefine.entity.SubTableEntity;
import com.jodinfo.outmirror.api.tabledefine.entity.TableDefineEntity;
import com.jodinfo.outmirror.api.tabledefine.entity.TableDefineTransactionEntity;
import com.jodinfo.outmirror.api.tabledefine.util.TableDefineUtil;
import com.jodinfo.outmirror.api.taskdyformpermission.entity.TaskDyformPermissionEntity;
import com.jodinfo.outmirror.api.taskdyformpermission.service.TaskDyformPermissionQueryService;
@Service(value="tableDefineBizService")
public class TableDefineBizServiceImpl implements TableDefineBizService {
    private static final Logger logger = LoggerFactory.getLogger(TableDefineBizServiceImpl.class);
 	
 	@Resource(name="tableDefineDmlService")
	private TableDefineDmlService tableDefineDmlService;
	@Resource(name="tableDefineQueryService")
	private TableDefineQueryService tableDefineQueryService;
	@Resource(name="dymcformQueryService")
	DymcformQueryService dymcformQueryService;
	@Resource(name="tableDefineTransactionService")
	TableDefineTransactionService tableDefineTransactionService;
	@Resource(name="columnDefineQueryService")
	ColumnDefineQueryService columnDefineQueryService;
	@Resource(name="columnDefineDmlService")
	ColumnDefineDmlService columnDefineDmlService;
	@Resource(name="dymcformDmlService")
	DymcformDmlService dymcformDmlService;
	@Resource(name="taskDyformPermissionQueryService")
	TaskDyformPermissionQueryService taskDyformPermissionQueryService;

	
	/** 
	 * 
	 * @author shensu
	 * @date 2016年12月30日 上午9:15:36
	 * @see com.jodinfo.outmirror.implementation.tabledefine.TableDefineBizService#addTableDefine(TableDefineEntity tableDefineEntity)
	 * @param TableDefineEntity tableDefineEntity
	 * @return int
	 */
	public ResponseEntity addTableDefine(TableDefineEntity tableDefineEntity) {
			ResponseEntity rs = new ResponseEntity(SysConstant.SUCCESS, "操作成功");
			try{
				 tableDefineEntity =TableDefineUtil.initTableDefineEntity(tableDefineEntity);
//				 TableDefineTransactionEntity tableDefineTransactionEntity = new TableDefineTransactionEntity();
//				 tableDefineTransactionEntity.setTableDefineEntity(tableDefineEntity);
				 //tableDefineTransactionEntity =  saveToRedis(tableDefineTransactionEntity);
				// int i = tableDefineTransactionService.addTableDefineAndAddColumnDefine(tableDefineTransactionEntity.getTableDefineEntity(), tableDefineTransactionEntity.getAddColumnDefineList());
				 int i =  tableDefineDmlService.addTableDefine(tableDefineEntity);
				 rs.setMessage(i+"条记录操作成功");
				 rs.setResult(JSON.parseObject(JSON.toJSONString(tableDefineEntity),Map.class));
			 }catch(AbstractGenericException e){
				logger.error(e.getFullMessage());
				rs.setStatus(SysConstant.FAIL).setMessage(e.getFullMessage());
			}catch(Exception e){
				String errorMessage = StringUtils.toString(e);
				logger.error(errorMessage);
				rs.setStatus(SysConstant.FAIL).setMessage(errorMessage);
			}
		return rs;
	}
	
	/**
	 * 将表定义存入redis
	 * @author shensu
	 * @date 2017年3月27日 下午5:17:21
	 * @param tableDefineEntity
	 */
	private TableDefineTransactionEntity  saveToRedis(TableDefineTransactionEntity tableDefineTransactionEntity ) {
		String htmlCode = tableDefineTransactionEntity.getTableDefineEntity().getHtmlCode();
		List<ColumnDefineEntity> columnDefineList  = parserHtmlCode(htmlCode,tableDefineTransactionEntity.getTableDefineEntity().getDymcformId());
		tableDefineTransactionEntity.setOriginalColumnDefineList(columnDefineList);
		//子表列的组装
		List<SubTableDefineEntity> subColumnDefineList = parserHtmlCode(htmlCode,tableDefineTransactionEntity.getTableDefineEntity());
		tableDefineTransactionEntity.setSubTableList(subColumnDefineList);
		tableDefineTransactionEntity = concateDDLSql(tableDefineTransactionEntity);
		logger.debug("最终组装DDL语句为:{} ",tableDefineTransactionEntity.getDdlSql());
		logger.debug("最终组装子表DDL语句为:{} ",tableDefineTransactionEntity.getSubtableDdlSql());
		List<String> listSqls  = new ArrayList<String>();
		if(org.apache.commons.lang3.StringUtils.isNotBlank(tableDefineTransactionEntity.getDdlSql())){
			listSqls.add(tableDefineTransactionEntity.getDdlSql());
			if(org.apache.commons.lang3.StringUtils.isNotBlank(tableDefineTransactionEntity.getSubtableDdlSql())){
				listSqls.add(tableDefineTransactionEntity.getSubtableDdlSql());
			}
			dymcformDmlService.batchExecuteDdlSqls(listSqls);
		}
		return  tableDefineTransactionEntity;
	}

	/**
	 * 
	 * 解析html,抽取出子表
	 * @author cao.weiwei
	 * @date 2017年4月14日 上午9:56:03
	 * @param htmlCode
	 * @param tableDefineEntity
	 * @return
	 */
	private List<SubTableDefineEntity> parserHtmlCode(String htmlCode,
			TableDefineEntity tableDefineEntity) {
		List<SubTableDefineEntity> list = new ArrayList<SubTableDefineEntity>();
		Document doc = Jsoup.parse(htmlCode);
	       Elements  els =  doc.getElementsByAttribute(TableDefineConstant.PLUGINS);
	       for(Element e:els){
	    	   if(e.attr(TableDefineConstant.PLUGINS).equals(TableDefineConstant.CONTROL_SUBTABLE)){
	    		   Base64 base64 = new Base64();
	    		   String subStr = new String(base64.decodeFast(e.attr(TableDefineConstant.SUBTABLEATTR)));
	    		   List<SubTableEntity> subtablelist = JSONArray.parseArray(subStr,SubTableEntity.class); 
	    		  String subtableName = tableDefineEntity.getTableName()+"_zb_"+e.attr("name");
	    		  list.add(buildSubTableDefineEntity(subtablelist,subtableName));
	    	   }
	       }
		return list;
	}

	/**
	 * 
	 * 组建子表对象SubTableDefineEntity
	 * @author cao.weiwei
	 * @date 2017年4月14日 上午10:25:23
	 * @param subtablelist
	 * @param subtableName
	 * @return
	 */
	public SubTableDefineEntity  buildSubTableDefineEntity( List<SubTableEntity> subtablelist,String subtableName){
		 SubTableDefineEntity  subtabledefine = new SubTableDefineEntity();
		 subtabledefine.setSubTableName(subtableName);
		 List<ColumnDefineEntity> columnlist = new  ArrayList<ColumnDefineEntity>();
		 for(SubTableEntity sub: subtablelist){
			 if(TableDefineConstant.SUBTABLE_COLUMN_TYPE_5.equals(sub.getSubDbColumnType())){
				 
			 }else{
				 ColumnDefineEntity column = new  ColumnDefineEntity();
				   column.setColumnComment(sub.getSubDbColumnComment());
				   column.setColumnLength(sub.getSubDbColumnLength());
				   column.setColumnName(sub.getSubDbColumnName());
				   column.setColumnType(TableDefineConstant.DEFAULT_TYPE);
				   column.setOldcolumnName(sub.getOldubDbColumnName());
				   columnlist.add(column);
			 }
		  
	    }
		 subtabledefine.setOriginalColumnDefineList(columnlist);
		 return subtabledefine;
	}
	/**
	 * 组装ddl语句
	 * @author shensu
	 * @date 2017年3月30日 下午4:06:21
	 * @param tableDefineTransactionEntity
	 * @return
	 */
	private TableDefineTransactionEntity concateDDLSql(TableDefineTransactionEntity tableDefineTransactionEntity) {
		
		boolean tableExist = checkTableIsExist(tableDefineTransactionEntity.getTableDefineEntity());
		if(!tableExist){
			tableDefineTransactionEntity = cancatCreateSubTableSqlAll(tableDefineTransactionEntity);
			tableDefineTransactionEntity = concatCreateSql(tableDefineTransactionEntity);
		}else{
			//不允许更新
			throw new BusinessException("0","表已经存在");
//			tableDefineTransactionEntity = cancatUpdateSubTableSqlAll(tableDefineTransactionEntity);
//			tableDefineTransactionEntity = concateUpdateSql(tableDefineTransactionEntity);
		}
		return tableDefineTransactionEntity;
	}
	/**
	 * 组装所有子表更新DDL sql
	 * @author cao.weiwei
	 * @date 2017年4月14日 下午2:17:31
	 * @param tableDefineTransactionEntity
	 * @return
	 */
	private TableDefineTransactionEntity cancatUpdateSubTableSqlAll(TableDefineTransactionEntity tableDefineTransactionEntity) {
		List<SubTableDefineEntity> subtableList = tableDefineTransactionEntity.getSubTableList();
		StringBuffer sql = new StringBuffer();
		if(!CollectionUtils.isEmpty(subtableList)){
			 for(SubTableDefineEntity subtable: subtableList){
				 boolean subtableExist = checkSubTableIsExist(subtable);
				 if(!subtableExist){
					 sql.append(concateSubTableCreateSql(subtable)); 
				 }else{
					 sql.append(concateSubTableUpdateSql(subtable));
				 }
			 }
		 }
		tableDefineTransactionEntity.setSubtableDdlSql(sql.toString());
		return tableDefineTransactionEntity;
	}
	/**
	 * 
	 * 组装新增所有子表DDL语句
	 * @author cao.weiwei
	 * @date 2017年4月14日 下午2:34:14
	 * @param tableDefineTransactionEntity
	 * @return
	 */
	private TableDefineTransactionEntity cancatCreateSubTableSqlAll(TableDefineTransactionEntity tableDefineTransactionEntity) {
		List<SubTableDefineEntity> subtableList = tableDefineTransactionEntity.getSubTableList();
		StringBuffer sql = new StringBuffer();
		if(!CollectionUtils.isEmpty(subtableList)){
			 for(SubTableDefineEntity subtable: subtableList){
				sql.append(concateSubTableCreateSql(subtable)); 
			 }
		 }
		tableDefineTransactionEntity.setSubtableDdlSql(sql.toString());
		return tableDefineTransactionEntity;
	}

	/**
	 * 拼接更新sql并存储在redis中
	 * @author shensu
	 * @date 2017年3月30日 下午5:25:07
	 * @param tableDefineTransactionEntity
	 * @return
	 */
	private TableDefineTransactionEntity concateUpdateSql(TableDefineTransactionEntity tableDefineTransactionEntity) {
		tableDefineTransactionEntity = findNeedChangeColumn(tableDefineTransactionEntity);
		tableDefineTransactionEntity.setDdlSql(dymcformQueryService.extractUpdateTableDDLsql(tableDefineTransactionEntity.getTableDefineEntity(), tableDefineTransactionEntity.getAddColumnDefineList(),tableDefineTransactionEntity.getUpdateColumnDefineList()));
		return tableDefineTransactionEntity;
	}
	
	/**
	 * 
	 * 组装子表更新语句
	 * @author cao.weiwei
	 * @date 2017年4月14日 下午1:54:05
	 * @param subTableDefineEntity
	 * @return
	 */
	private String concateSubTableUpdateSql(SubTableDefineEntity subTableDefineEntity){
		subTableDefineEntity = findNeesChangeSubTableColumn(subTableDefineEntity);
		return dymcformQueryService.extractUpdateSubTableDDLsql(subTableDefineEntity);
	}
	/**
	 *
	 * 组装子表新增语句
	 * @author cao.weiwei
	 * @date 2017年4月14日 下午1:54:31
	 * @param subtableDefine
	 * @return
	 */
	private String concateSubTableCreateSql(SubTableDefineEntity  subtableDefine){
		return dymcformQueryService.extractCreateSubTableDDLsql(subtableDefine);
	}

	/**
	 * 拼接创建sql并存储在redis中
	 * @author shensu
	 * @date 2017年3月30日 下午3:09:37
	 * @param tableDefineEntity
	 * @param columnDefineList
	 * @param sql
	 * @return
	 */
	private TableDefineTransactionEntity concatCreateSql(TableDefineTransactionEntity tableDefineTransactionEntity) {
		boolean needCreateTime = true;
		TableDefineEntity tableDefineEntity  = tableDefineTransactionEntity.getTableDefineEntity();
		List<ColumnDefineEntity> columnDefineList = tableDefineTransactionEntity.getOriginalColumnDefineList();
		tableDefineTransactionEntity.setDdlSql(dymcformQueryService.extractCreateTableDDLsql(tableDefineEntity, columnDefineList));
		tableDefineTransactionEntity.setAddColumnDefineList(addDefValuecolumnDefineList(tableDefineEntity.getDymcformId(),columnDefineList,needCreateTime));
		return tableDefineTransactionEntity;
	}

	/**
	 * 添加默认值
	 * @author shensu
	 * @date 2017年3月31日 下午3:32:03
	 * @param columnDefineList
	 * @return
	 */
	private List<ColumnDefineEntity> addDefValuecolumnDefineList(String dymcformId,List<ColumnDefineEntity> columnDefineList,boolean needCreateTime) {
		for(ColumnDefineEntity columnDefineEntity:columnDefineList){
			columnDefineEntity.setUpdateTime(DateUtils.getCurrentTime());
			columnDefineEntity.setDymcformId(dymcformId);
			if(needCreateTime){
			 columnDefineEntity.setCreateTime(DateUtils.getCurrentTime());
			}
		}
		return columnDefineList;
	}

	/**
	 * 查询出需要修改的列
	 * @author shensu
	 * @param TableDefineTransactionEntity tableDefineTransactionEntity 
	 * @date 2017年3月30日 下午2:06:33
	 * @param TableDefineTransactionEntity tableDefineTransactionEntity
	 * @return
	 */
	private TableDefineTransactionEntity  findNeedChangeColumn(TableDefineTransactionEntity tableDefineTransactionEntity) {
		ColumnDefineEntity columnDefineEntity = new ColumnDefineEntity();
		List<ColumnDefineEntity> updateColumnDefineList = new ArrayList<ColumnDefineEntity>();
		columnDefineEntity.setDymcformId(tableDefineTransactionEntity.getTableDefineEntity().getDymcformId());
		List<ColumnDefineEntity> dbcolumnDefineList =  columnDefineQueryService.queryAllColumnDefine(columnDefineEntity);
		List<ColumnDefineEntity> originalColumnDefineList = tableDefineTransactionEntity.getOriginalColumnDefineList();
		for(ColumnDefineEntity dbcolumnDefineEntity:dbcolumnDefineList){
			for(ColumnDefineEntity originalColumnDefineEntity:originalColumnDefineList){
				if(dbcolumnDefineEntity.getColumnName().equals(originalColumnDefineEntity.getColumnName())||(dbcolumnDefineEntity.getColumnName().equals(originalColumnDefineEntity.getOldcolumnName()))){
					updateColumnDefineList.add(originalColumnDefineEntity);
				}
			}
		}
		
		tableDefineTransactionEntity.setUpdateColumnDefineList(updateColumnDefineList);
		originalColumnDefineList.removeAll(updateColumnDefineList);
		tableDefineTransactionEntity.setAddColumnDefineList(originalColumnDefineList);
		return tableDefineTransactionEntity;
	}
	
	/**
	 * 查询出需要修改的子表字段
	 * @author cao.weiwei
	 * @date 2017年4月14日 上午11:49:29
	 * @param subTableDefineEntity
	 * @return
	 */
	private SubTableDefineEntity findNeesChangeSubTableColumn(SubTableDefineEntity subTableDefineEntity){
		// 查询数据库列数据
		List<Map<String,Object>> dbcolumns = dymcformQueryService.queryTableType(subTableDefineEntity.getSubTableName());
		Map<String,Object> map = coverListAsMap(dbcolumns,"columnName");
		List<ColumnDefineEntity> columnList = subTableDefineEntity.getOriginalColumnDefineList();
		List<ColumnDefineEntity> updateColumns = new ArrayList<ColumnDefineEntity>();
		List<ColumnDefineEntity> addColumns = new ArrayList<ColumnDefineEntity>();
		for(ColumnDefineEntity column: columnList){
			if(map.containsKey(column.getColumnName())){
				updateColumns.add(column);
			}else{
				addColumns.add(column);
			}
		}
		return subTableDefineEntity;
	}
	/**
	 * 
	 *  list 转map
	 * @author cao.weiwei
	 * @date 2017年4月14日 下午3:27:50
	 * @param list
	 * @param keyName
	 * @return
	 */
	private Map<String,Object> coverListAsMap(List<Map<String,Object>> list,String keyName){
		Map<String,Object> map = new HashMap<String,Object>();
		if(!CollectionUtils.isEmpty(list)){
			for(Map<String,Object> m: list){
				map.put(m.get(keyName).toString(), m);
			}
		}
		return map;
	}

	/**
	 * 检查表是否存在
	 * @author shensu
	 * @date 2017年3月29日 下午3:37:42
	 * @param tableDefineEntity
	 * @return
	 */
	private boolean checkTableIsExist(TableDefineEntity tableDefineEntity) {
		if(tableDefineEntity!=null&&org.apache.commons.lang3.StringUtils.isNotBlank(tableDefineEntity.getTableName())){
			return dymcformQueryService.checkTableIsExist(tableDefineEntity.getTableName());
		}else if(tableDefineEntity==null){
			throw new WebException("200001", "tableDefineEntity为空，无法获取tableName");
		}else{
			throw new WebException("200002", "tableDefineEntity中tableName为空");
		}
	}
	/**
	 * 检查子表是否存在
	 * @author cao.weiwei
	 * @date 2017年4月14日 下午1:30:22
	 * @param subTableDefineEntity
	 * @return
	 */
	private boolean checkSubTableIsExist(SubTableDefineEntity subTableDefineEntity) {
		if(subTableDefineEntity!=null&&org.apache.commons.lang3.StringUtils.isNotBlank(subTableDefineEntity.getSubTableName())){
			return dymcformQueryService.checkTableIsExist(subTableDefineEntity.getSubTableName());
		}else if(subTableDefineEntity==null){
			throw new WebException("200001", "subTableDefineEntity为空，无法获取tableName");
		}else{
			throw new WebException("200002", "subTableDefineEntity中tableName为空");
		}
	}

	/**
	 * 解析html
	 * @author shensu
	 * @date 2017年3月28日 下午4:27:01
	 * @return
	 */
	private List<ColumnDefineEntity> parserHtmlCode(String htmlCode,String dymcformId) {
		List<ColumnDefineEntity> list = new ArrayList<ColumnDefineEntity>();
		   Document doc = Jsoup.parse(htmlCode);
		   String column_key = "columnname";
		   String column_type = "columntype";
		   String column_length = "columnlength";
		   String column_comment = "columncomment";
		   String old_columnName = "oldcolumnName";
		   String isrequired = "isrequired";
		   String isquery = "isquery";
		   String ishidden = "ishidden";
		   String precision = "precision";// 精度
		   String validrule = "validrule";//验证规则
		   String isdel = "isdel";
		   String islist = "islist";
		   String isflowvar = "isflowvar";
		   String description = "description";//注释
	       Elements  els =  doc.getElementsByAttribute(column_key);
	       for(Element element:els){
	    	   ColumnDefineEntity columnDefineEntity = new ColumnDefineEntity();
	    	   columnDefineEntity.setDymcformId(dymcformId);
	    	   columnDefineEntity.setColumnName(element.attr(column_key));
	    	   columnDefineEntity.setColumnType(element.attr(column_type));
	    	   columnDefineEntity.setColumnLength(element.attr(column_length));
	    	   columnDefineEntity.setOldcolumnName(element.attr(old_columnName));
	    	   if(org.apache.commons.lang3.StringUtils.isNotBlank(element.attr(isdel))){
	    		   columnDefineEntity.setIsDel(element.attr(isdel));
	    	   }else{
	    		   columnDefineEntity.setIsDel(SysConstant.FAIL);
	    	   }
	    	   if(org.apache.commons.lang3.StringUtils.isNotBlank(element.attr(isrequired))){
	    		   columnDefineEntity.setIsRequired(element.attr(isrequired));
	    	   }else{
	    		   columnDefineEntity.setIsRequired(SysConstant.FAIL);
	    	   }
	    	   if(org.apache.commons.lang3.StringUtils.isNotBlank(element.attr(isquery))){
	    		   columnDefineEntity.setIsQuery(element.attr(isquery));
	    	   }else{
	    		   columnDefineEntity.setIsQuery(SysConstant.FAIL);
	    	   }
	    	   if(org.apache.commons.lang3.StringUtils.isNotBlank(element.attr(ishidden))){
	    		   columnDefineEntity.setIsHidden(element.attr(ishidden));
	    	   }else{
	    		   columnDefineEntity.setIsHidden(SysConstant.FAIL);
	    	   }
	    	   if(org.apache.commons.lang3.StringUtils.isNotBlank(element.attr(precision))){
	    		   columnDefineEntity.setColumnPrecision(element.attr(precision));
	    	   }
	    	   if(org.apache.commons.lang3.StringUtils.isNotBlank(element.attr(validrule))){
	    		   columnDefineEntity.setValidrule(element.attr(validrule));
	    	   }
	    	   if(org.apache.commons.lang3.StringUtils.isNotBlank(element.attr(islist))){
	    		   columnDefineEntity.setIsList(element.attr(islist));
	    	   }else{
	    		   columnDefineEntity.setIsList(SysConstant.FAIL);
	    	   }
	    	   if(org.apache.commons.lang3.StringUtils.isNotBlank(element.attr(isflowvar))){
	    		   columnDefineEntity.setIsFlowVar(element.attr(isflowvar));
	    	   }else{
	    		   columnDefineEntity.setIsFlowVar(SysConstant.FAIL);
	    	   }
	    	   if(org.apache.commons.lang3.StringUtils.isNotBlank(element.attr(description))){
	    		   columnDefineEntity.setDescription(element.attr(description));
	    		   columnDefineEntity.setColumnComment(element.attr(description));
	    	   }else{
	    		   columnDefineEntity.setDescription(element.attr(""));
	    		   columnDefineEntity.setColumnComment("");
	    	   }
	    	   list.add(columnDefineEntity);
	       }
		return list;
	}


	/** 
	 * 
	 * @author shensu
	 * @date 2016年12月30日 上午9:15:36
	 * @see com.jodinfo.outmirror.implementation.tabledefine.TableDefineBizService#updateTableDefine(TableDefineEntity tableDefineEntity)
	 * @param TableDefineEntity tableDefineEntity
	 * @return ResponseEntity
	 */
	public ResponseEntity updateTableDefine(TableDefineEntity tableDefineEntity) {
		 ResponseEntity rs = new ResponseEntity(SysConstant.SUCCESS, "操作成功");
			try{
				tableDefineEntity =TableDefineUtil.initTableDefineEntity(tableDefineEntity);
				// 查询chuID
				TableDefineEntity t = new TableDefineEntity();
				t.setTableName(tableDefineEntity.getTableName());
				TableDefineEntity table = tableDefineQueryService.queryByEntity(t);
				if(table==null) throw new BusinessException("0", "未查到TableDefineEntity");
				tableDefineEntity.setId(table.getId());
//				TableDefineTransactionEntity tableDefineTransactionEntity = new TableDefineTransactionEntity();
//				tableDefineTransactionEntity.setTableDefineEntity(tableDefineEntity);
//				tableDefineTransactionEntity =  saveToRedis(tableDefineTransactionEntity);
				int i = tableDefineDmlService.updateTableDefine(tableDefineEntity);
				rs.setMessage(i+"条记录操作成功");
				 rs.setResult(JSON.parseObject(JSON.toJSONString(tableDefineEntity),Map.class));
			 }catch(AbstractGenericException e){
				logger.error(e.getFullMessage());
				rs.setStatus(SysConstant.FAIL).setMessage(e.getFullMessage());
			}catch(Exception e){
				String errorMessage = StringUtils.toString(e);
				logger.error(errorMessage);
				rs.setStatus(SysConstant.FAIL).setMessage(errorMessage);
			}
		return rs;
	}
	/** 
	 * 
	 * @author shensu
	 * @date 2016年12月30日 上午9:15:36
	 * @see com.jodinfo.outmirror.implementation.tabledefine.TableDefineBizService#queryAllTableDefine(TableDefineEntity tableDefineEntity)
	 * @param TableDefineEntity tableDefineEntity
	 * @return String
	 */
	public String queryAllTableDefine(TableDefineEntity tableDefineEntity) {
		return JSON.toJSONString(tableDefineQueryService.queryAllTableDefine(tableDefineEntity));
	} 
	/** 
	 * 
	 * @author shensu
	 * @date 2016年12月30日 上午9:15:36
	 * @see com.jodinfo.outmirror.implementation.tabledefine.TableDefineBizService#queryAllTableDefine(TableDefineEntity tableDefineEntity)
	 * @param TableDefineEntity tableDefineEntity
	 * @return PageResult
	 */
	public String queryListForPageTableDefine(TableDefineEntity tableDefineEntity) {
		return new PageResult( tableDefineQueryService.queryListForPageTableDefine(tableDefineEntity), tableDefineQueryService.queryCountTableDefine(tableDefineEntity)).toString();
	} 
	/** 
	 * 
	 * @author shensu
	 * @date 2016年12月30日 上午9:15:36
	 * @see com.jodinfo.outmirror.implementation.tabledefine.TableDefineQueryService#queryById(TableDefineEntity tableDefineEntity)
	 * @param BigInteger id
	 * @return
	 */
	public TableDefineEntity queryById(BigInteger id) {
		return tableDefineQueryService.queryById(id);
	}
	
	public void exportTableDefine(TableDefineEntity tableDefineEntity, HttpServletResponse response) {
		List<TableDefineEntity> exportList = null;
		String ids = tableDefineEntity.getIds();
		if (ValidationUtil.isNullOrEmptyString(ids)) {
			exportList =tableDefineQueryService.queryAllTableDefine(tableDefineEntity);
		} else {
			String[] idArray = ids.split(",");
			List<BigInteger> idList = new ArrayList<BigInteger>();
			for(String id : idArray) {
				idList.add(new BigInteger(id));
			}
			exportList = tableDefineQueryService.queryByIds(idList);
			// 将字典中的code转换为name
		   //convertCodeToName(exportList);
		}
		ExcelExport.exportExcel(exportList, "TableDefineEntityExcel", "TableDefineEntity信息", response);
	}

	/** 
	 * 
	 * @author shensu
	 * @date 2017年3月27日 上午10:59:10
	 * @see com.jodinfo.outmirror.api.tabledefine.service.TableDefineBizService#queryEntityByTableDefine(com.jodinfo.outmirror.api.tabledefine.entity.TableDefineEntity)
	 * @param tableDefineEntity
	 * @return
	 */
	 public TableDefineEntity queryEntityByTableDefine(TableDefineEntity tableDefineEntity) {
		 return tableDefineQueryService.queryByEntity(tableDefineEntity);
	    }
	/**    
	 * 遍历解析自定义控件
	 * @param htmlCode
	 * @param tableId  表数据id
	 * @param tableName 表名
	 * @return
	 */
    private String buildElements(String htmlCode,String tableId,String tableName
    		,String workFlowId,String taskKey,String taskId){
        Document doc = Jsoup.parseBodyFragment(htmlCode);
        JSONObject  permissionJson =  getTaskDyformPermission(workFlowId, taskKey);
        String columnKey ="columnname";
        setElementsPermission(doc, permissionJson, columnKey);
        Elements els = doc.getElementsByAttribute("plugins");
        for(Element e: els){
        	String attr = e.attr("plugins");
        	String name = e.attr("name");
        	e.attr("value","");
        	String permissionCode = "2";
        	if(permissionJson!=null){
        		permissionCode = permissionJson.getString(name);
        	}
        	if(TableDefineConstant.CONTROL_UPLOADFILE.equals(attr)){
        		coverUploadfile(e,permissionCode);
        	}else if(TableDefineConstant.CONTROL_MACROS.equals(attr)){
        		coverMacros(e,permissionCode);
        	}else if(isSelector(attr)){
        		coverSelect(e,permissionCode);
        	}else if(TableDefineConstant.CONTROL_SUBTABLE.equals(attr)){
        		coverSubtable(e,tableId,tableName,permissionCode);
        	}else if(TableDefineConstant.CONTROL_IDSELECT.equals(attr)){
        		coverIdselect(e,permissionCode);
        	}
        }
        return doc.toString();
    }
    
    /**
     * 判断是否是选择器
     * @author cao.weiwei
     * @date 2017年4月23日 下午2:30:59
     * @param plugins
     * @return
     */
    private boolean isSelector(String plugins){
    	boolean is = false;
    	if(TableDefineConstant.CONTROL_SHOPSELECT.equals(plugins)){
    		is = true;
    	}else if(TableDefineConstant.CONTROL_DEPTSELECT.equals(plugins)){
    		is = true;
    	}else if(TableDefineConstant.CONTROL_PEOPLESELECT.equals(plugins)){
    		is = true;
    	}
    	return is;
    }
    
	/**
     * 设置表单节点权限
     * @author cao.weiwei
     * @date 2017年4月21日 下午2:53:29
     * @param doc
     * @param permissionJson
     * @param columnKey
     */
	private void setElementsPermission(Document doc, JSONObject permissionJson,
			String columnKey) {
		Elements  columnels =  doc.getElementsByAttribute(columnKey);
        for(Element e: columnels){
        	String permissionCode = "2";
        	if(permissionJson!= null){
        		permissionCode = permissionJson.getString(e.attr(columnKey));
        	}
        	if("1".equals(permissionCode)){ // 编辑
        		
        	}else if("2".equals(permissionCode)){ // 只读
        		e.attr("readonly","readonly");
        		e.attr("required","false");
        	}else if("3".equals(permissionCode)){ // 隐藏 
        		e.attr("class","mini-hidden "+e.attr("class"));
        		e.attr("required","false");
        	}
        }
	}

    /**
     * 查询权限
     * @author cao.weiwei
     * @date 2017年4月21日 下午2:43:54
     * @param workFlowId
     * @param taskKey
     * @return
     */
	private JSONObject getTaskDyformPermission(String workFlowId, String taskKey) {
		TaskDyformPermissionEntity taskDyformPermission = new TaskDyformPermissionEntity();
        taskDyformPermission.setTaskKey(taskKey);
        taskDyformPermission.setWorkflowId(workFlowId);
        if(StringUtils.isEmpty(taskKey)||StringUtils.isEmpty(workFlowId)){
        	return null;
        }
        taskDyformPermission = taskDyformPermissionQueryService.queryByEntity(taskDyformPermission);
        JSONObject permissionObj = new JSONObject();
        if(taskDyformPermission!=null && taskDyformPermission.getPermission()!=null){
        	permissionObj = JSON.parseObject(taskDyformPermission.getPermission());
        }
        return permissionObj;
	}
    
    /**
     * id选择器
     * @author cao.weiwei
     * @date 2017年4月19日 下午1:44:25
     * @param e
     * @param coverIdselect
     */
    private void coverIdselect(Element e,String permissionCode){
    	IdWorker idWorker = new IdWorker(0,0);
    	String prefix = e.attr(TableDefineConstant.PREFIX.trim());
    	e.attr("value",prefix+idWorker.nextId());
    	setNodePermission(e, permissionCode);
    }
    /**
     * 
     * 解析字表控件
     * @author cao.weiwei
     * @date 2017年4月12日 下午5:09:27
     * @param e
     * @param tableId
     * @param tableName
     * @param permissionCode
     * @return
     */
    private Element coverSubtable(Element e,String tableId,String tableName,String permissionCode){
    	String id = e.attr("id");
    	String name = e.attr("name");
    	String subHtml = e.attr("subtableattr");
    	Base64 Base64 = new Base64();
    	subHtml  = new String(Base64.decodeFast(subHtml));
    	List<SubTableEntity> subTableData = JSONArray.parseArray(subHtml,SubTableEntity.class);
    	String datagridid = name+"_datagrid";
    	if(!StringUtils.isEmpty(e.attr("gridtitle"))) e.before(createTableTitle(e.attr("gridtitle"),permissionCode));
    	if(!StringUtils.isEmpty(e.attr("addevent"))){
    		String addbtid = tableName+"_addbt_"+datagridid;
    		e.before(createAddButton(addbtid,e.attr("addevent"),permissionCode));
    	}
    	if(!StringUtils.isEmpty(e.attr("delevent"))){
    		String delbtid = tableName+"_delbt_"+datagridid;
    		e.before(createDelButton(delbtid,e.attr("delevent"),permissionCode));
    	}
    	Element div = createDatagrid(datagridid,name,permissionCode);
    	div.attr("url","${projectName}/DymcformDisplayAdmin/getSubTableData?tableName="+tableName+"_zb_"+name+"&mainTableId="+tableId);
		List<String> linkurls = new ArrayList<String>();
    	createDatagridColumns(name, subTableData, datagridid, div,linkurls,permissionCode);
		e.after(div);
		e.attr("class","mini-hidden "+e.attr("class"));
		e.attr("type","hidden");
		
    	return e;
    }

    /**
     * 
     * 创建datagrid的内容
     * @author cao.weiwei
     * @date 2017年4月14日 下午3:49:54
     * @param name
     * @param subTableData
     * @param datagridid
     * @param div
     * @param linkurls 表格中含有的url
     * @param permissionCode
     */
	private void createDatagridColumns(String name, List<SubTableEntity> subTableData,
			String datagridid, Element div,List<String> linkurls,String permissionCode) {
		Element columndiv = new Element(Tag.valueOf("div"),"");
		columndiv.attr("property","columns");
		div.appendChild(columndiv);
		if(!CollectionUtils.isEmpty(subTableData)){
			ListSortUtil<SubTableEntity> sort = new ListSortUtil<SubTableEntity>();
			sort.sortByIntType(subTableData, "subDbColumnseq", "asc");
			columndiv.append("<div type='indexcolumn'></div><div type='checkcolumn'></div> ");
	    	for( SubTableEntity row: subTableData){
	    		if(TableDefineConstant.DATA_TYPE_5.equals(row.getSubDbColumnType())){
	    			if(!StringUtils.isEmpty(row.getLinkurl())){
	    				JSONObject jsonObj = JSON.parseObject(row.getLinkurl());
	    				if(SysConstant.SUCCESS.equals(jsonObj.getString("isPermis"))){
	    					if(SysConstant.PERMISSION_EDIT.equals(permissionCode)){
	    						linkurls.add(row.getLinkurl());
	    			    	}else if(SysConstant.PERMISSION_READONLY.equals(permissionCode)){
	    			    	}else if(SysConstant.PERMISSION_HIDDEN.equals(permissionCode)){
	    			    	}
	    				}else{
	    					linkurls.add(row.getLinkurl());
	    				}
	    				
	    			}
	    		}else{
	    			Element column = createColumnDiv(name, datagridid, row);
		    		columndiv.appendChild(column);
	    		}
	    	}
	    	if(!CollectionUtils.isEmpty(linkurls)){
	    		columndiv.appendChild(createOptColumnDiv(linkurls));
	    	}
		}
	}

	/**
	 * 创建操作列
	 * @author cao.weiwei
	 * @date 2017年4月26日 下午4:04:15
	 * @param linkurls
	 * @param columndiv
	 */
	private Element createOptColumnDiv(List<String> linkurls) {
		Element column = new Element(Tag.valueOf("div"),"");// input的外层
		column.attr("headerAlign","center");
		column.attr("allowSort","true");
		column.text("操作");
		column.attr("field",JSON.toJSONString(linkurls));
		column.attr("renderer","onRendererUrl");
		return column;
	}

	/**
	 * 
	 * 创建可编辑列
	 * @author cao.weiwei
	 * @date 2017年4月14日 下午3:54:13
	 * @param name
	 * @param datagridid
	 * @param row
	 * @return
	 */
	private Element createColumn(String name, String datagridid,
			SubTableEntity row,List<String> linkurls) {
		Element outter = new Element(Tag.valueOf("div"),"");// input的外层
		outter.attr("headerAlign","center");
		Element inner = new Element(Tag.valueOf("input"),"");// input
		inner.attr("property","editor");
		inner.attr("style","width:100%;");
		if(!StringUtils.isEmpty(row.getSubDbColumnName())){
			outter.attr("name",row.getSubDbColumnName().toUpperCase());
			outter.attr("field",row.getSubDbColumnName().toUpperCase());
		}
		if(!StringUtils.isEmpty(row.getSubDbColumnComment()))outter.text(row.getSubDbColumnComment());
		setSubTableColumnType(name,row, outter, inner,linkurls);
		outter.appendChild(inner);
		return outter;
	}
	/**
	 * 创建datagrid的表头
	 * @author cao.weiwei
	 * @date 2017年4月24日 下午6:33:12
	 * @param name
	 * @param datagridid
	 * @param row
	 * @param linkurls
	 * @return
	 */
	private Element createColumnDiv(String name, String datagridid,
			SubTableEntity row) {
		Element column = new Element(Tag.valueOf("div"),"");// input的外层
		column.attr("field",org.apache.commons.lang3.StringUtils.upperCase(row.getSubDbColumnName()));
		column.attr("headerAlign","center");
		column.attr("allowSort","true");
		column.text(row.getSubDbColumnComment());
		String type = row.getSubDbColumnType();
		if(TableDefineConstant.SUBTABLE_COLUMN_TYPE_2.equals(type)){
			column.attr("class","mini-datepicker");
			column.attr("dateFormat","yyyy-MM-dd");
		}else if(TableDefineConstant.SUBTABLE_COLUMN_TYPE_3.equals(type)){
			column.attr("class","mini-spinner");
		}else if(TableDefineConstant.SUBTABLE_COLUMN_TYPE_4.equals(type)){
			column.attr("class","mini-textbox");
			column.attr("visible","false");
		}else if(TableDefineConstant.SUBTABLE_COLUMN_TYPE_5.equals(row.getSubDbColumnType())){

		}
		return column;
	}

	/**
	 * 
	 * 设置子表控件的列的类型
	 * @author cao.weiwei
	 * @date 2017年4月14日 下午3:53:28
	 * @param name 子表名
	 * @param row
	 * @param outter
	 * @param inner
	 */
	private void setSubTableColumnType(String name,SubTableEntity row, Element outter, Element inner,List<String> linkurls) {
		String type = row.getSubDbColumnType();
		if(TableDefineConstant.SUBTABLE_COLUMN_TYPE_1.equals(type)){
			inner.attr("class","mini-textbox");
		}else if(TableDefineConstant.SUBTABLE_COLUMN_TYPE_2.equals(type)){
			inner.attr("class","mini-datepicker");
			outter.attr("dateFormat","yyyy-MM-dd");
		}else if(TableDefineConstant.SUBTABLE_COLUMN_TYPE_3.equals(type)){
			inner.attr("class","mini-spinner");
		}else if(TableDefineConstant.SUBTABLE_COLUMN_TYPE_4.equals(type)){
			inner.attr("class","mini-textbox");
			outter.attr("visible","false");
		}else if(TableDefineConstant.SUBTABLE_COLUMN_TYPE_5.equals(type)){
			// 事件名字: 控件名+列名+click
			inner.attr("class","mini-buttonedit");
			inner.attr("emptyText","请输入...");
			inner.attr("onbuttonclick",name+row.getSubDbColumnName()+"click");
			linkurls.add("<script type=\"text/javascript\"src=\""+row.getLinkurl()+"\"></script>");
		}else if(TableDefineConstant.SUBTABLE_COLUMN_TYPE_6.equals(type)){
			inner.attr("class","mini-textbox");
			outter.attr("renderer","javascript:function('${projectName}')");
		}else if(TableDefineConstant.SUBTABLE_COLUMN_TYPE_7.equals(type)){
			inner.attr("class","mini-textbox");
			outter.attr("renderer","onActionRenderer"+TableDefineConstant.SUBTABLE_COLUMN_TYPE_7);
		}else if(TableDefineConstant.SUBTABLE_COLUMN_TYPE_8.equals(type)){
			inner.attr("class","mini-textbox");
			outter.attr("renderer","onActionRenderer"+TableDefineConstant.SUBTABLE_COLUMN_TYPE_8);
		}else{
			inner.attr("class","mini-textbox");
		}
	}

    /**
     * 
     * 创建datagrid
     * @author cao.weiwei
     * @date 2017年4月14日 下午3:43:30
     * @param datagridid
     * @param name 子表控件名称
     * @param permissionCode 权限码
     * @return
     */
	private Element createDatagrid(String datagridid,String name,String permissionCode) {
	
		Element div = new Element(Tag.valueOf("div"),"");
    	div.attr("id",datagridid);//id
    	div.attr("class","mini-datagrid");
    	div.attr("style","width:100%;height:300px;");
    	div.attr("idField","id");
    	div.attr("showFooter","false");
    	div.attr("showPager","false");
    	div.attr("multiSelect","true");
    	div.attr("allowSortColumn","false");
    	
    	div.attr("allowCellEdit","true");
    	div.attr("allowCellSelect","true");
    	div.attr("multiSelect","true");
    	div.attr("editNextOnEnterKey","true");
    	div.attr("editNextRowCell","true");
    	
		setDatagridPermission(permissionCode, div);
		return div;
	}

	/**
	 * 设置表格的权限
	 * @author cao.weiwei
	 * @date 2017年4月21日 下午3:42:17
	 * @param permissionCode
	 * @param div
	 */
	private void setDatagridPermission(String permissionCode, Element div) {
		if(SysConstant.PERMISSION_EDIT.equals(permissionCode)){
			div.attr("allowCellEdit","true");
    	}else if(SysConstant.PERMISSION_READONLY.equals(permissionCode)){
    		div.attr("allowCellEdit","false");
    	}else if(SysConstant.PERMISSION_HIDDEN.equals(permissionCode)){
    		div.attr("class","mini-hidden "+div.attr("class"));
    	}
	}

    /**
     * 创建删除按钮
     * @author cao.weiwei
     * @date 2017年4月14日 下午3:42:08
     * @param buttonId
     * @param delevent
     * @param permissionCode
     * @return
     */
	private Element createDelButton(String buttonId,String delevent, String permissionCode) {
		Element delE = new Element(Tag.valueOf("a"),"");
		delE.attr("class","mini-button");
		delE.attr("iconCls","icon-remove");
		delE.attr("onclick",delevent);
		delE.attr("id",buttonId);
		delE.text("删除");
		setDelButtonPermission(delE, permissionCode);
		return delE;
	}

	/**
	 * 设置删除按钮的权限
	 * @author cao.weiwei
	 * @date 2017年4月21日 下午3:30:32
	 * @param delE
	 * @param permissionCode
	 */
    private void setDelButtonPermission(Element delE, String permissionCode) {
    	if(SysConstant.PERMISSION_EDIT.equals(permissionCode)){
    		
    	}else if(SysConstant.PERMISSION_READONLY.equals(permissionCode)){
    		delE.attr("class","mini-hidden");
    	}else if(SysConstant.PERMISSION_HIDDEN.equals(permissionCode)){
    		delE.attr("class","mini-hidden");
    	}
		
	}

	/**
     * 
     * 创建新增按钮 
     * @author cao.weiwei
     * @date 2017年4月14日 下午3:40:39
     * @param buttonId
     * @param addevent
     * @param permissionCode
     * @return
     */
	private Element createAddButton(String buttonId,String addevent, String permissionCode) {
		Element addE = new Element(Tag.valueOf("a"),"");
		addE.attr("class","mini-button");
		addE.attr("iconCls","icon-add");
		addE.attr("onclick",addevent);
		addE.attr("id",buttonId);
		addE.text("增加");
		setAddButtonPermission(addE, permissionCode);
		return addE;
	}
	/**
	 * 设置新增按钮的权限
	 * @author cao.weiwei
	 * @date 2017年4月21日 下午3:28:17
	 * @param addE
	 * @param permissionCode
	 */
    private void setAddButtonPermission(Element addE, String permissionCode) {
    	if(SysConstant.PERMISSION_EDIT.equals(permissionCode)){
    		
    	}else if(SysConstant.PERMISSION_READONLY.equals(permissionCode)){
    		addE.attr("class","mini-hidden "+addE.attr("class"));
    	}else if(SysConstant.PERMISSION_HIDDEN.equals(permissionCode)){
    		addE.attr("class","mini-hidden "+addE.attr("class"));
    	}
		
	}

	/**
     * 创建表格标题
     * @author cao.weiwei
     * @date 2017年4月18日 下午1:00:50
     * @param titleName
     * @param permissionCode
     * @return
     */
	private Element createTableTitle(String titleName,String permissionCode) {
		Element title = new Element(Tag.valueOf("h3"),"");
		title.text(titleName);
		title.attr("class","gridtitle");
		setNodePermission(title, permissionCode);
		return title;
	}
	
    /**
     * 上传控件解析
     * @param e
     * @param permissionCode权限
     * @return
     */
    private Element coverUploadfile(Element e,String permissionCode){
		String fileLimit = e.attr("fileLimit");
        Element e2 = new Element(Tag.valueOf("a"), "");
        e2.attr("iconCls","icon-attachement");
        e2.attr("plain","true");
        e2.attr("class","mini-button");
        e2.text("附件");
        e2.attr("onclick","openFileListWindow('"+fileLimit+"','"+e.attr("name")+"','${projectName}',true)");
        if(SysConstant.PERMISSION_EDIT.equals(permissionCode)){
			
    	}else if(SysConstant.PERMISSION_READONLY.equals(permissionCode)){
    		e2.attr("onclick","openFileListWindow('"+fileLimit+"','"+e.attr("name")+"','${projectName}',false)");
    		e2.attr("required","false");
    	}else if(SysConstant.PERMISSION_HIDDEN.equals(permissionCode)){
    		e2.attr("class","mini-hidden "+e2.attr("class"));
    		e2.attr("required","false");
    	}
        
       // setNodePermission(e2, permissionCode);
        e.after(e2);
        e.attr("type","hidden");
        e.attr("class","mini-hidden "+e.attr("class"));
        return e;
    }
    
    /**
     * 解析宏控件
     * @param e
     * @param permissionCode
     * @return
     */
    private	 Element coverMacros(Element e,String permissionCode){
    	setNodePermission(e, permissionCode);
		String datatype = e.attr("datatype");
    	if(TableDefineConstant.DATA_TYPE_1.equals(datatype)){ // 当前时间
    		e.attr("value",DateUtils.getCurrentTime());
    		e.attr("class","mini-datepicker "+e.attr("class"));
    		e.attr("format","yyyy-MM-dd HH:mm:ss");
    	    e.attr("timeFormat","HH:mm:ss");
    		e.attr("showTime","true");
    	}else if(TableDefineConstant.DATA_TYPE_2.equals(datatype)){//当前日期
    		e.attr("value",DateUtils.getCurrentTime().substring(0, 10));
    		e.attr("class","mini-datepicker "+e.attr("class"));
    		e.attr("format","yyyy-MM-dd");
    	}else if(TableDefineConstant.DATA_TYPE_3.equals(datatype)){//当前登录用户名
    		e.attr("value",((IPlatformUser)UserContext.getUser()).getName());
    	}else if(TableDefineConstant.DATA_TYPE_4.equals(datatype)){//当前组织机构名
    		e.attr("value",((IPlatformUser)UserContext.getUser()).getOrgName());
    	}else if(TableDefineConstant.DATA_TYPE_5.equals(datatype)){//当前登录用户ID
    		e.attr("value",((IPlatformUser)UserContext.getUser()).getUserNo());
    	}else if(TableDefineConstant.DATA_TYPE_6.equals(datatype)){//当前组织机构ID
    		e.attr("value",((IPlatformUser)UserContext.getUser()).getOrgId());
    	}
    	return e;
    }

    /**
     * 设置单个节点的属性
     * @author cao.weiwei
     * @date 2017年4月21日 下午3:18:46
     * @param e
     * @param permissionCode
     */
	private void setNodePermission(Element e, String permissionCode) {
		if(SysConstant.PERMISSION_EDIT.equals(permissionCode)){
			
    	}else if(SysConstant.PERMISSION_READONLY.equals(permissionCode)){
    		e.attr("readonly","readonly");
    		e.attr("required","false");
    	}else if(SysConstant.PERMISSION_HIDDEN.equals(permissionCode)){
    		e.attr("class","mini-hidden "+e.attr("class"));
    		e.attr("required","false");
    	}
	}
    /**
     * 选择器转换(部门选择器,人员选择器,店铺选择器)
     * @author cao.weiwei
     * @date 2017年4月23日 下午2:06:53
     * @param e
     * @param permissionCode
     * @return
     */
    private Element coverSelect(Element e ,String permissionCode){
    	String vluefield = e.attr("valuefield");
		Element a = new Element(Tag.valueOf("a"), "");
		a.text("选择");
		a.attr("class","icon-myselect");
		a.attr("href","javascript:open"+e.attr(TableDefineConstant.PLUGINS)+"Window('"+e.attr("conditions")+"','"+e.attr("name")+"','"+vluefield+"','${projectName}')");
		e.after(a);
		setSelectNodePermission(e,a, permissionCode);
	return e;
}
    /**
     * 设置选择器的权限
     * @author cao.weiwei
     * @date 2017年4月22日 下午2:08:19
     * @param e
     * @param permissionCode
     */
    private void setSelectNodePermission(Element e, Element a, String permissionCode) {
		if(SysConstant.PERMISSION_EDIT.equals(permissionCode)){
			
    	}else if(SysConstant.PERMISSION_READONLY.equals(permissionCode)){
    		e.attr("readonly","readonly");
    		a.attr("class","mini-hidden");
    		e.attr("required","false");
    	}else if(SysConstant.PERMISSION_HIDDEN.equals(permissionCode)){
    		e.attr("class","mini-hidden "+e.attr("class"));
    		a.attr("class","mini-hidden");
    		e.attr("required","false");
    	}
	}
    
	/** 
	 * 
	 * @author shensu
	 * @date 2017年4月4日 上午8:56:12
	 * @see com.jodinfo.outmirror.api.tabledefine.service.TableDefineBizService#distinctRow(java.util.List)
	 * @param subTableEntity
	 * @return
	 */
	public ResponseEntity distinctRow(List<SubTableEntity> subTableEntitys) {
		ResponseEntity rs = new ResponseEntity(SysConstant.SUCCESS,"操作成功");
		HashSet<String> hs1 = new HashSet<String>(); 

		for(SubTableEntity subTableEntity : subTableEntitys){
			hs1.add(JSON.toJSONString(subTableEntity));
		}
		subTableEntitys.clear();
		for(String str : hs1){
			if(!"{}".equalsIgnoreCase(str)){
				subTableEntitys.add(JSON.parseObject(str, SubTableEntity.class));
			}
		}
		ListSortUtil<SubTableEntity> sort = new ListSortUtil<SubTableEntity>();
		sort.sort(subTableEntitys, "subDbColumnseq", "asc");
	    Map<String, Object> map = new HashMap<String, Object>();
		map.put("data",subTableEntitys);
		rs.setResult(map);
		return rs;
	}

	public TableDefineEntity queryAnalysisEntityByTableDefine(
		TableDefineEntity tableDefineEntity,HttpServletRequest request) {
		// 变量
		String pkvalue = request.getParameter("pkvalue");
		String taskId = request.getParameter("taskId");
		String workFlowId = request.getParameter("workFlowId");
		String taskKey = request.getParameter("taskKey");
		TableDefineEntity tabledefine = tableDefineQueryService.queryByEntity(tableDefineEntity);
		String scripts = request.getSession().getAttribute("scripts").toString();
		String projectName = request.getSession().getAttribute("projectName").toString();
		String cdnAddress = request.getSession().getAttribute("cdnAddress").toString();
		String cacheVersion = request.getSession().getAttribute("cacheVersion").toString();
		
        if(tabledefine!=null){
            String htmlCode = tabledefine.getHtmlCode();
            htmlCode = buildElements(htmlCode,pkvalue,tabledefine.getTableName(),workFlowId,taskKey,taskId);
            // 替换html中scripts, projectName
            htmlCode = htmlCode.replaceAll("\\$\\{projectName\\}", projectName);
            htmlCode = htmlCode.replaceAll("\\$\\{scripts\\}", scripts);
            htmlCode = htmlCode.replaceAll("\\$\\{cdnAddress\\}", cdnAddress);
            htmlCode = htmlCode.replaceAll("\\$\\{cacheVersion\\}", cacheVersion);
            tabledefine.setHtmlCode(htmlCode);
        }
        return tabledefine;
	}

	/**
	 * 
	 * 
	 * @author cao.weiwei
	 * @date 2017年4月20日 下午3:33:57
	 * @see com.jodinfo.outmirror.api.tabledefine.service.TableDefineBizService#generateTable(com.jodinfo.outmirror.api.tabledefine.entity.TableDefineEntity)
	 * @param tableDefineEntity
	 * @return
	 */
	public ResponseEntity generateTable(TableDefineEntity tableDefineEntity) {
		ResponseEntity rs = new ResponseEntity(SysConstant.SUCCESS, "操作成功");
		try{
			 tableDefineEntity = tableDefineQueryService.queryByEntity(tableDefineEntity);
			 if(tableDefineEntity==null) throw new BusinessException("0","未查询到保存的数据");
			 TableDefineTransactionEntity tableDefineTransactionEntity = new TableDefineTransactionEntity();
			 tableDefineTransactionEntity.setTableDefineEntity(tableDefineEntity);
			 tableDefineTransactionEntity =  saveToRedis(tableDefineTransactionEntity);
			 int i = 0;
			 if(!CollectionUtils.isEmpty(tableDefineTransactionEntity.getAddColumnDefineList())){
				 i = columnDefineDmlService.addColumnDefineList(tableDefineTransactionEntity.getAddColumnDefineList());
			 }
			 tableDefineEntity.setIsDeployed(SysConstant.SUCCESS);
			 tableDefineDmlService.updateTableDefine(tableDefineEntity);
			 rs.setMessage(i+"条记录操作成功");
			 rs.setResult(JSON.parseObject(JSON.toJSONString(tableDefineEntity),Map.class));
		 }catch(AbstractGenericException e){
			logger.error(e.getFullMessage());
			rs.setStatus(SysConstant.FAIL).setMessage(e.getFullMessage());
		}catch(Exception e){
			String errorMessage = StringUtils.toString(e);
			logger.error(errorMessage);
			rs.setStatus(SysConstant.FAIL).setMessage(errorMessage);
		}
	return rs;
	}
	
}

